import datetime
import logging

import sentry_sdk
from flasgger import Swagger
from flask import Flask, request
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from sentry_sdk.integrations.flask import FlaskIntegration

from app.base_pb import base_bp
from app.extensions import (
    JSONProvider,
    JsonResponse,
    get_loghandler_config,
    get_swagger_config,
)
from db.base_model import db

sentry_sdk.init(
    dsn="https://fe815f26bcf4f92380ebadf35c872fa1@o4505834101080064"
    ".ingest.sentry.io/4505834104815616",
    integrations=[FlaskIntegration()],
    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for performance monitoring.
    # We recommend adjusting this value in production.
    traces_sample_rate=1.0,
    # Set profiles_sample_rate to 1.0 to profile 100%
    # of sampled transactions.
    # We recommend adjusting this value in production.
    profiles_sample_rate=1.0,
)

app = Flask(__name__)

app = Flask(__name__)
CORS(app, supports_credentials=True)
bcrypt = Bcrypt(app)
app.config["BCRYPT_WORK_FACTOR"] = 8
app.register_blueprint(base_bp)
jwt = JWTManager(app)
app.config["SECRET_KEY"] = "1qaz2wsx3edc"
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = datetime.timedelta(days=15)

app.json_provider_class = JSONProvider  # 数据类型特处理，如自定义时间格式
app.response_class = JsonResponse  # 返回数据自动json序列化

template_config, swagger_config = get_swagger_config()
Swagger(app, config=swagger_config, template=template_config)


@app.before_request
def log_request():
    try:
        db.connect()
    except Exception as e:
        app.logger.info(f"connect db error {e}, retry")
        db.connect()
    # 记录请求信息到日志
    app.logger.info(f"{request.method} {request.path} {request.remote_addr}")


@app.teardown_request
def teardown_request(exception):
    db.close()


if __name__ != "__main__":
    gunicorn_logger = logging.getLogger("gunicorn.error")  # logger对象，gunicorn.error记录器
    logging.root.setLevel(gunicorn_logger.level)

if __name__ == "__main__":
    app.logger.addHandler(get_loghandler_config())
    app.run(port=12222, host="0.0.0.0", debug=True)
